import { AlipayCircleOutlined, TaobaoCircleOutlined, WeiboCircleOutlined } from '@ant-design/icons';
import { Alert, Checkbox, Form, Row, Col,Input,message } from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import React, { Component ,useEffect} from 'react';
import {tokenLogin} from './service'

import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { Dispatch } from 'redux';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import Link from 'umi/link';
import { connect } from 'dva';
import { StateType } from './model';
import LoginComponents from './components/Login';
import styles from './style.less';
import { getCaptcha } from './service';
// import * as fresnsClient from '../../../../fresns.client.json';

const { Tab, UserName, Password, Mobile, Captcha, Submit } = LoginComponents;
var fileInput  = document.getElementById("fileInput");

interface LoginProps {
  dispatch: Dispatch<any>;
  userAndlogin: StateType;
  submitting: boolean;
}
interface LoginState {
  type: string;
  autoLogin: boolean;
  token:string;
  email:string;
  captchaUrl:string;
  captchaKey:string;
  captchaString: string;
  fileUrl: string;
}
export interface FormDataType {
  name: string;
  password: string;
  mobile: string;
  captcha: string;
  captchaKey: string;
  captchaUrl:string;
  fileUrl: string;
}

export interface FormDataTypeToken {
  token:string;
  email:string;
}

class Login extends Component<LoginProps, LoginState> {
  loginForm: FormComponentProps['form'] | undefined | null = undefined;

  state: LoginState = {
    type: 'account',
    autoLogin: true,
    token:'',
    email:'',
    captchaUrl:'',
    captchaKey:'',
    captchaString:'',
    fileUrl: '../../../../fresns.client',
  };

  

  componentDidMount(){
    // console.log('admin login');
    // console.log(fresnsClient)
    // localStorage.setItem('fresnsClient',fresnsClient);
    // localStorage.setItem('platform',fresnsClient.platform);
    // localStorage.setItem('appId',fresnsClient.appId);
    // localStorage.setItem('appKey',fresnsClient.appKey);
    // this.tokenEmailLogin
    // this.freshCaptcha();
    // this.getFileContent()
  }

  changeAutoLogin = (e: CheckboxChangeEvent) => {
    this.setState({
      autoLogin: e.target.checked,
    });
  };

  handleSubmit = (err: any, values: FormDataType) => {
    const { type,captchaString } = this.state;
    if (!err) {
      const { dispatch } = this.props;
      // values.captchaKey = '$2y$10$yCTvH2Tjy6uLVKARp25ugO2nh0HgRL2natKGJg6bsvHRlrz2i/dRW';
      // values.captcha = 'zyre';
      // values.captcha = captchaKey;
      // values.captchaKey = captchaString;
      console.log(values);
      dispatch({
        type: 'userAndlogin/login',
        payload: {
          ...values,
          type,
        },
      });
    }
  };

  onTabChange = (type: string) => {
    this.setState({ type });
  };

  //获取验证码
  freshCaptcha = () => {
    getCaptcha().then(res=>{
      this.setState({
        captchaUrl: res.data.fileUrl,
        captchaString: res.data.key
      })
    })
  }
  
  //读取文件
  getFileContent = () => {
    const reader = new FileReader();
  }

  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      if (!this.loginForm) {
        return;
      }
      this.loginForm.validateFields(['mobile'], {}, (err: any, values: FormDataType) => {
        if (err) {
          reject(err);
        } else {
          const { dispatch } = this.props;
          ((dispatch({
            type: 'userAndlogin/getCaptcha',
            payload: values.mobile,
          }) as unknown) as Promise<any>)
            .then(resolve)
            .catch(reject);
        }
      });
    });

  renderMessage = (content: string) => (
    <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
  );

  render() {
    const { userAndlogin, submitting } = this.props;
    const { code, type: loginType, msg } = userAndlogin;
    const { type, autoLogin, captchaUrl } = this.state;

    console.log('userAndlogin--->',userAndlogin)
    return (
      <div className={styles.main}>
        <LoginComponents
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          ref={(form: any) => {
            this.loginForm = form;
          }}
        >
          <Tab
            key="account"
            tab={formatMessage({ id: 'userandlogin.login.tab-login-credentials' })}
          >
            {code !== 0 &&
              loginType === 'account' &&
              !submitting &&
              this.renderMessage(
                msg || ''
              )}
            <UserName
              name="name"
              placeholder={`${formatMessage({ id: 'App ID' })}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'App ID 必填' }),
                },
              ]}
            />
            <Password
              name="password"
              placeholder={`${formatMessage({ id: 'App Secret' })}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'App Secret 必填' }),
                },
              ]}
              onPressEnter={e => {
                e.preventDefault();
                if (this.loginForm) {
                  this.loginForm.validateFields(this.handleSubmit);
                }
              }}
            />                               
          </Tab>
          <Submit loading={submitting}>
            <FormattedMessage id="userandlogin.login.login" />
          </Submit>
        </LoginComponents>
      </div>
    );
  }
}

export default connect(
  ({
    userAndlogin,
    loading,
  }: {
    userAndlogin: StateType;
    loading: {
      effects: {
        [key: string]: boolean;
      };
    };
  }) => ({
    userAndlogin,
    submitting: loading.effects['userAndlogin/login'],
  }),
)(Login);
